package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-04-11
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {

        //校验参数
        if (dto == null || (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //是否包含手机号和密码
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {

            //根据登录的名称查询数据库是否有该用户
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(queryWrapper);
            if (ObjectUtils.isEmpty(one)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            //比对密码
            String pwd = dto.getPassword() + one.getSalt();
            String md5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
            if (!md5.equals(one.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 密码一致,使用jwt生成token
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", one.getId());
            String token = AppJwtUtil.getToken(userInfo);

            //返回前端数据，排除敏感字段
            HashMap map = new HashMap();
            ApUser user = new ApUser();
            user.setName(one.getName());
            user.setId(one.getId());
            map.put("user", user);
            map.put("token", token);

            return ResponseResult.okResult(map);

        }

        if (!StringUtils.isEmpty(dto.getEquipmentId())) {

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", 0);
            String token = AppJwtUtil.getToken(userInfo);
            HashMap map = new HashMap();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService userFollowService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;

    /**
     * 关注作者，取消关注
     * @param dto
     */
    @Override

    public ResponseResult follow(UserRelationDto dto) {

        //构建关注表对象
        ApUserFollow follow = new ApUserFollow();

        //从本地线程中取
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser = this.getById(user.getUserId());
        follow.setUserId(apUser.getId());
        follow.setUserName(apUser.getName());
        follow.setLevel(1);
        follow.setCreatedTime(new Date());
        //根据作者id查找自媒体id,自媒体id和用户id是一样的
        ResponseResult<ApAuthor> authorResponseResult = articleFeign.getAuthor(dto.getAuthorId());
        if (authorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor author = authorResponseResult.getData();
            follow.setFollowId(author.getWmUserId());
            follow.setFollowName(author.getName());
        }

        // 判断当前登录用户与关注作者是否已经有历史记录
        LambdaQueryWrapper<ApUserFollow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUserFollow::getFollowId, follow.getFollowId());
        queryWrapper.eq(ApUserFollow::getUserId, follow.getUserId());
        ApUserFollow one = userFollowService.getOne(queryWrapper);
        if (one == null) {
            //判断是关注，新增记录
            if (dto.getOperation() == 0) {
                //保存关注记录
                userFollowService.save(follow);
            }
        } else {
            //如果是取消关注
            if (dto.getOperation() == 1) {
                userFollowService.remove(queryWrapper);
            }
        }

        //发送消息到kafka
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setFollowId(follow.getFollowId());
        followBehaviorDto.setOperation(dto.getOperation());
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        String json = JSON.toJSONString(followBehaviorDto);
        kafkaTemplate.send(followBehaviorTopic, json);
        return ResponseResult.okResult();
    }


}
